<?php
/**
 * $Id: cms_controller.php 1005 2011-11-09 06:26:32Z manu $
 * 
 * This file can not be redistributed to anyone without the permission of Giga Promoters
 * Copyright 2005 - 2008, Giga Promoters
 * 						  608 Aggarwal Cyber Plaza
 *						  Netaji Subhash Place, Delhi - 110034
 *						  www.gigapromoters.com
 * 
 *
 * @version 			$Rev: 1005 $
 * @lastModifiedBy		$LastChangedBy: manu $
 * @lastChanged			$Date: 2011-11-09 11:56:32 +0530 (Wed, 09 Nov 2011) $
 * @copyright 			Giga Promoters (www.gigapromoters.com)
 * 
 */

class CmsController extends CmsAppController {
	
	var $name = 'Cms';
	var $uses = array();
	var $helpers = array('Html','Form', 'Javascript', 'Cms.Index');
	var $components = array('RequestHandler');
	var $logDir = null;
	
	function beforeFilter()
	{
		parent::beforeFilter();
		// disable dump for this controller
		$this->saveDump = false;
		$this->logDir = TMP.'logs'.DS;
	}
	
	/**
	 * Shows listing of dump files ordered by time
	 *
	 */
	function showDump()
	{
		$this->layout = '';
		$controllerDumpRecords = array();
		$logs = file(TMP.'logs'.DS.'controllerDump.log');
		$this->set('dumpFile', $logs);
		
	}
	
	/**
	 * View specific dump file
	 *
	 * @param unknown_type $uuid
	 */
	function viewDump($uuid, $controllerOnly = false)
	{
		$logFile = 'controllerDump_'.$uuid;
		$contents = unserialize(cache($logFile));
		if($controllerOnly)
		{
			//unset($contents->Component);
		}
		prd($contents);
	}
	
	function clearAll()
	{
		$folder = new Folder(TMP);
		//$folder = Folder::cd(TMP);
		$dumpFiles = $folder->find('controllerDump*');
		prd($dumpFiles);
	}

	function offline()
	{
		$out =  cr('cmsConfig.Backend.siteOfflineText');
		if($out == '')
		{
			$out = "<h3>".cr('cmsConfig.Backend.siteName')." is offline.</h3>";
		}
		echo $out;
		exit;
	}

	function admin_logs()
	{
		$this->pageTitle = __("Cms logs");
		uses('Folder');
		$Folder =& new Folder($this->logDir);
		$files = $Folder->ls();
		$this->set('files',$files);
	}

	function admin_viewLog($fileName,$download =0)
	{
		$this->pageTitle = __("View log");
		$file =  $file = $this->logDir.$fileName.'.log';	
		$content = file_get_contents($file);
		if($download == 1)
		{
			$fileName = __($fileName); 
			 header("Content-type: text/plain");
             header("Content-Disposition: attachment; filename=\"$fileName.log\"");
             echo $content;
             exit;
		}
		$this->set('fileName',$fileName);
		$this->set('content',$content);
	}


	function admin_clearLog($log)
	{
		$file = $this->logDir.$log.'.log';	
		if(file_exists($file) && unlink($file))
		{
			$this->successMsg(__('Log cleared successfully!'));
		}
		else
		{
			$this->errorMsg(__('Unable to clear log!'));
		}
		$this->redirect('/admin/cms/logs/',true);
	}
	
	function report($entity, $entity_id)
	{
		
		$newReport = array(
			'Report' => array(
				'entity' => $entity,
				'entity_id' => $entity_id
		)
		);
		ClassRegistry::init('Cms.Report')->save($newReport);
		exit;
	}

		/**
admin_listLogs(); // this will show list of all log files inside /app/tmp/logs same as pages module you just did
admin_viewLog($log) // this will show select log file
admin_clearLog($log); // this function will empty contents of the log without deleting the file

		*/
	
	function startTestSession()
	{
		if(Configure::read('debug') == 0)
		{
			echo "Action not allowed";
			exit;
		}
		require_once(CAKE.'tests'.DS.'lib'.DS.'giga_web_test_case_operations.php');
		$this->Session->write('ignoreCaptcha', true);
		
		$testId = mt_rand(1, 1000);
		$this->Session->write('tester_id', $testId);
		require_once(CONFIGS.'database.php');
		$dbConfig = new DATABASE_CONFIG;
		$srcDb = $dbConfig->default['database'];
		$targetDb = $srcDb.'_slave_'.$testId;
		exec("gmw add_mysql_slave ".$srcDb." ".$targetDb);
		echo "Started: --".$testId."--";
		exit;
	}
	
	function endTestSession()
	{
		if(Configure::read('debug') == 0)
		{
			echo "Action not allowed";
			exit;
		}
		$this->Session->delete('ignoreCaptcha');
		$this->Session->delete('tester_id');
		$dbConfig = new DATABASE_CONFIG;
		$targetDb = $dbConfig->webtest['database'];
		mysql_query('DROP DATABASE '.$targetDb);
		exit;
	}
	
	function test_emails()
	{
		$this->layout = '';
		if(!cr('webtest_id'))
		{
			echo "No test session present"; exit;
		}
		$conditions = array(
			'TestEmail.tester_id' => cr('webtest_id')
		);
		$this->set('emails', cri('Cms.TestEmail')->find('all', compact('conditions')));
	}
	
	function clear_test_emails()
	{
		cri('Cms.TestEmail')->deleteAll('1=1');
		exit;
	}

	/*
		Exports table row's  in xml format 
	*/
	function admin_export()
	{
		App::import('Vendor','Cms.DbShift');
		$dbShiftObj = new DbShift();
		$output = $dbShiftObj->exportAllTables();
		header("Content-type: text/xml");
		$fileName = Configure::read('cmsConfig.Database.database').'.xml';
		header("Content-Disposition: attachment; filename=\"$fileName\"");
		Configure::write('debug',0);
		echo $output;
		exit;
	}


	function admin_import()
	{
		if(isset($this->data['Cms']['file']['name']) && $this->data['Cms']['file']['name'] != null)
		{
			App::import('Vendor','Cms.DbShift');
			$dbShiftObj = new DbShift();
			ignore_user_abort();
			$fileContent = file_get_contents($this->data['Cms']['file']['tmp_name']);
			//@unlink($this->data['Cms']['file']['tmp_name']);
			try
			{
				$dbShiftObj->importAll($fileContent);
				$this->successMsg(__("File has been imported."));
			}Catch(Exception $e)
			{
					$this->errorMsg(sprintf(__("File was not imported completely. Error: %s"),$e->getMessage()));
			}
		}
	}
	
	function compress($fileHash,$type = 'css')
	{
		$this->layout = false;	
		$fileName = 'compressed_'.$fileHash.'_'.$type;
		$fullFilePath = COMPRESSED_FILE_DIR.$fileName;
		$files = null;
		if(file_exists($fullFilePath))
		{
			$files = @unserialize(file_get_contents($fullFilePath));
		}
		$cachekey = $fileHash."_$type"."_content";
		if($files)
		{
			Cache::set(array('path'=>CACHE,'duration'=>"+30 seconds"));
			App::import('Vendor','Cms.ContentCompressor');
			$content = Cache::read($cachekey);
			if(!$content)
			{
				$content  = array();
				$ContentCompressor = new ContentCompressor($type);
				foreach($files as $file)
				{
					$content[] =  $ContentCompressor->compress($file);
				}
				Cache::write($cachekey,$content);
			}
		}else
		{
			$this->cakeError('error404');
		}
		$this->set(compact('content','type'));
		$this->RequestHandler->renderAs($this,$type);
	}
	
	function admin_clearCache()
	{
		$path = TMP . 'cache';
		$folder = & new Folder($path);
		$tree = $folder->tree($path, false);
        foreach ($tree as $files)
        {
        	foreach ($files as $file)
            {
            	 if (!is_dir($file))
                {
                    $file = & new File($file);
                    $file->delete();
                }
                
            }
        }
		$this->successMsg(__('System cache has been refreshed.'));
		$this->redirect(cr('Backend.adminLoginRedirect'));
		
	}
	
	function horizontalInput($count)
	{
		Configure::write('debug', 0);
		$count = str_replace('.css', '', $count);
		header("Content-type: text/css");
		$this->layout = '';
		$this->set(compact('count'));
	}
	
	function getOptions($field, $val)
	{
		Configure::write('debug', 0);
		$fieldOriginal = $field;
		list($model, $field) = explode('.', $field);
		$modelObj = Utility::getModelObject($model);
	
		// check if $field is a 'parent' type field
		if($modelObj->getFieldProperty($field, 'type') == 'parent')
		{
			$childInfo = $modelObj->getFieldProperty($field, 'childInfo');
			$modelObj = Utility::getModelObject($childInfo['model']);
			$field = end(explode('.', $fieldOriginal));
		}
		
		$trigger = $modelObj->getFieldProperty($field, 'triggers');

		$updateFields = $trigger['onChange']['update'];
		if(is_string($updateFields))
		{
			$updateFields = array($updateFields);
		}
		
		$json = array();
		foreach($updateFields as $fieldToUpdate)
		{
			$modelMethod = 'get'.Inflector::camelize($fieldToUpdate).'Options';
			$options = $modelObj->{$modelMethod}($val);
			$json[$fieldToUpdate] = $options;
		}
		echo json_encode($json); exit;
	}	
}
?>